//
//  CSTransferDetailController.m
//  JiFengDaRen
//
//  Created by SH_iOS on 2017/9/19.
//  Copyright © 2017年 SH_iOS. All rights reserved.
//
//#import "BalanceViewController.h"
#import "BaseToolViewController.h"
#import "CSTransferDetailCell.h"
#import "CSPublicAccountModel.h"
#import "CSTransferDetailController.h"

@interface CSTransferDetailController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *transferPayTable;
@property(nonatomic,strong)CSTransferDetailCell *transferAmountCell;//收款银行
@property(nonatomic,strong)CSTransferDetailCell *bankNameCell;//收款银行
@property(nonatomic,strong)CSTransferDetailCell *nameCell;//收款人
@property(nonatomic,strong)CSTransferDetailCell *cardNoCell;//收款账号
@property(nonatomic,strong)CSTransferDetailCell *openingCankCell;//开户网点
@property(nonatomic,strong)CSTransferDetailCell *remarkCell;//备注
@property(nonatomic,strong)CSTransferDetailCell *laterFiveCardNoCell;//卡号最后5位

@property(nonatomic,strong)CSPublicAccountModel *publicAccountModel;

@property(nonatomic,strong)SHButton *paySuccessBtn;;

@end

@implementation CSTransferDetailController



- (UITableView *)transferPayTable{
    
    if (!_transferPayTable) {
        
        _transferPayTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - KNAVIGATIONBARHEIGHT) style:UITableViewStylePlain];
        _transferPayTable.estimatedRowHeight = 100;
        _transferPayTable.rowHeight = UITableViewAutomaticDimension;
        _transferPayTable.delegate = self;
        _transferPayTable.scrollEnabled = NO;
        _transferPayTable.dataSource = self;
        _transferPayTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_transferPayTable];
    }
    
    
    return _transferPayTable;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"VIP转账详情";
    self.view.backgroundColor = [UIColor whiteColor];
    [self transferPayTable];
    [self getPublicAccountInformation];
    
    SHButton *exitTaranferDetailVcBtn = [SHButton buttonWithType:UIButtonTypeCustom title:@"完成" font:14 titleColor: KREDCOLOR textAlignment:UIControlContentHorizontalAlignmentRight forState:UIControlStateNormal];
    exitTaranferDetailVcBtn.frame = CGRectMake(0, 0, __I6Width(40), __I6Width(40));
    [exitTaranferDetailVcBtn addTarget:self action:@selector(exitTaranferDetailVc:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:exitTaranferDetailVcBtn];

    // Do any additional setup after loading the view.
}

- (void)exitTaranferDetailVc:(UIBarButtonItem *)sende{
    
//    for (UIViewController *vc in self.rt_navigationController.rt_viewControllers) {
//        if ([vc isKindOfClass:[BalanceViewController class]]) {
//            [self.navigationController popToViewController:vc animated:YES];
//        }
//    }
    
}
#pragma mark - 获取对公账号
- (void)getPublicAccountInformation{
    
    [MyDataService requestAFURL:@"/data/api/public_account_information" httpMethod:@"GET" params:nil data:nil complection:^(id result) {
        
        if ([result[@"success"] boolValue]) {
            
            self.publicAccountModel = [CSPublicAccountModel mj_objectWithKeyValues:result[@"data"]];
            
        }else{
             [self.view makeToast:result[@"data"] duration:2 position:@"center"];
        }
        [self.transferPayTable reloadData];
    } failure:^(id erro) {
        
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return 7;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
     if(indexPath.row == 0) {
        
        _bankNameCell = [[CSTransferDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        
        _bankNameCell.labelText = @"收款银行";
        _bankNameCell.contentLabel.text = self.publicAccountModel.bankName;
        _bankNameCell.hiddenCopyBtn = YES;

        return _bankNameCell;
    }else if(indexPath.row == 1){
        
        _nameCell = [[CSTransferDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        
        _nameCell.labelText = @" 收款人";
         _nameCell.contentLabel.text = self.publicAccountModel.accountName;
        return _nameCell;
    }else if(indexPath.row == 2){
        
        _cardNoCell = [[CSTransferDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];

        _cardNoCell.labelText = @"收款账号";
        _cardNoCell.contentLabel.text = self.publicAccountModel.bankCode;
        return _cardNoCell;
    }else if(indexPath.row == 3){
        _openingCankCell = [[CSTransferDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        _openingCankCell.labelText = @"开户网点";
        _openingCankCell.contentLabel.text = self.publicAccountModel.bankSubName;

        return _openingCankCell;
    }else if(indexPath.row == 4){
        
        _remarkCell = [[CSTransferDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        _remarkCell.contentLabel.text = self.orderCode;
        _remarkCell.labelText = @"备注信息";

        return _remarkCell;
    }else if(indexPath.row == 5) {
        
        _laterFiveCardNoCell = [[CSTransferDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        _laterFiveCardNoCell.labelText = @"卡号后5位";
        _laterFiveCardNoCell.contentLabel.text = self.laterFiveCode;
        _laterFiveCardNoCell.hiddenCopyBtn = YES;
        return _laterFiveCardNoCell;
        
    }else{
        _transferAmountCell = [[CSTransferDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        
        _transferAmountCell.labelText = @"转账金额";
        _transferAmountCell.contentLabel.text = self.amount;
        return _transferAmountCell;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return __I6Height(15);
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, __I6Height(15))];
    headerView.backgroundColor = KBASEBGCOLOR;
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return __I6Height(200);
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *footView  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, __I6Height(200))];
    
//    SHButton *gotoPayBtn = [SHButton buttonWithType:UIButtonTypeCustom title:@"进入网银支付" font:15 titleColor:KREDCOLOR textAlignment:0 forState:UIControlStateNormal];
//    gotoPayBtn.layer.borderWidth =  0.5;
//    gotoPayBtn.layer.borderColor = KREDCOLOR.CGColor;
//    gotoPayBtn.layer.cornerRadius = __I6Width(21);
//
//    gotoPayBtn.layer.masksToBounds = YES;
//    [gotoPayBtn addTarget:self action:@selector(gotoPayBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
//    [footView addSubview:gotoPayBtn];
    
    
     _paySuccessBtn = [SHButton buttonWithType:UIButtonTypeCustom title:@"支付成功?" font:15 titleColor:  [UIColor whiteColor] textAlignment:0 forState:UIControlStateNormal];
  
//    paySuccessBtn.layer.borderWidth =  0.5;
//    paySuccessBtn.layer.borderColor = KREDCOLOR.CGColor;
    _paySuccessBtn.layer.cornerRadius = __I6Width(5);
    _paySuccessBtn.layer.masksToBounds = YES;
    _paySuccessBtn.backgroundColor = KREDCOLOR;
    [_paySuccessBtn addTarget:self action:@selector(paySuccessBtnClicked:) forControlEvents:UIControlEventTouchUpInside];

    [footView addSubview:_paySuccessBtn];

    
//    [gotoPayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(footView.mas_top).with.offset(__I6Height(25));
//        make.left.mas_equalTo(footView.mas_left).with.offset(__I6Width(25));
//        make.width.equalTo(@(__I6Width(120)));
//        make.height.equalTo(@(__I6Height(42)));
//        
//        
//    }];

    
    [_paySuccessBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(footView.mas_top).with.offset(__I6Height(25));
        make.centerX.mas_equalTo(footView.mas_centerX).with.offset(0);
        make.width.equalTo(@(__I6Width(326)));
        make.height.equalTo(@(__I6Height(42)));
        
    }];
    
    
    
     NSString *str =[NSString stringWithFormat:@"转账完成后,请一定要点击下方[支付成功?],否则金额不会到账;1小时内到账;如有疑问,请联系客服。"];
     UITextView  *textview = [[UITextView alloc]init];
     textview.userInteractionEnabled = NO;
     textview.text = str;
     // 设置段落
     NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
     paragraphStyle.lineSpacing = 2;
     paragraphStyle.alignment = NSTextAlignmentJustified;
     NSDictionary *attributes = @{ NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:@.5f};
     
     NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str attributes:attributes];
     [attributedString addAttribute:NSLinkAttributeName
     value:@""
     range:[[attributedString string] rangeOfString:@"[支付成功?]"]];
     [attributedString addAttribute:NSLinkAttributeName
     value:@""
     range:[[attributedString string] rangeOfString:@"否则金额不会到账"]];
    [attributedString addAttribute:NSLinkAttributeName
                             value:@""
                             range:[[attributedString string] rangeOfString:@"1小时内"]];
     UIFont *font = KSystemFont(__I6Width(13));
     
     
     [attributedString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, attributedString.length)];
     textview.attributedText = attributedString;
     textview.textColor = KSHTEXTCOLOR;
     textview.linkTextAttributes = @{NSForegroundColorAttributeName:  KREDCOLOR};
     //NSUnderlineColorAttributeName: [UIColor clearColor],
     //NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)
     
     textview.editable = NO;        //必须禁止输入，否则点击将弹出输入键盘
     textview.scrollEnabled = NO;

    
    
    [footView addSubview:textview];
    [textview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_paySuccessBtn.mas_bottom).with.offset(__I6Height(20));
        make.left.mas_equalTo(footView.mas_left).with.offset(__I6Width(25));
        make.right.mas_equalTo(footView.mas_right).with.offset(__I6Width(-20));
        
        
    }];


    return  footView;
}


#pragma mark - 去网银支付
- (void)gotoPayBtnClicked:(SHButton *)sender{
    
    if (self.publicAccountModel.payUrl.length == 0) {
        [Tool alertWithMessage:@"请复制信息,然后使用网银转账" title:@"提示" who:self];
    }else{
        
        BaseToolViewController * baseTool = [[BaseToolViewController alloc]init];
        
        baseTool.title = @"网银支付";
        baseTool.urlString = self.publicAccountModel.payUrl;
        
        [self.navigationController pushViewController:baseTool animated:YES];
    }
    
    
    
    
}
#pragma mark - 发送对账信息
- (void)paySuccessBtnClicked:(SHButton *)sender
{

    
    //UIAlertController风格：UIAlertControllerStyleAlert
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"
                                                                             message:@"请先在网银中支付,再点击按钮。你是否已完成支付？"
                                                                      preferredStyle:UIAlertControllerStyleAlert ];
    
    //添加取消到UIAlertController中
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"还没支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:cancelAction];
    
    //添加确定到UIAlertController中
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"已经支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            [self startTime];
            NSDictionary *params = @{@"orderId":self.orderCode,@"amount":self.amount};
            [MyDataService requestNoRSAAFURL:@"/data/api/send_sms_reconciliation" httpMethod:@"POST" params: params data:nil complection:^(id result) {
                
                if ([result[@"success"] boolValue]) {
                    
                    [self.view makeToast:@"已通知客服处理" duration:2.f position:@"center"];
                }
            } failure:^(id erro) {
                
            }];

            
            dispatch_sync(dispatch_get_main_queue(), ^{
                //Call method 2 to update the UI
                [alertController dismissViewControllerAnimated:YES completion:^(void){
                    //My mistake was: I was calling method 2 over here to update the UI
                    return;
                }];
            });
        });
        

        
        

    }];
    [alertController addAction:okAction];

    dispatch_async(dispatch_get_main_queue(), ^{
        
    });
    [self presentViewController:alertController animated:YES completion:nil];
    
    

    
}


- (void)startTime{
    
    __block int timeout = 50; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [_paySuccessBtn setTitle:@"支付完成?" forState:UIControlStateNormal];
                _paySuccessBtn.enabled = YES;
                [_paySuccessBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                _paySuccessBtn.backgroundColor = KREDCOLOR;
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                
                [_paySuccessBtn setTitle:[NSString stringWithFormat:@"%@S",strTime] forState:UIControlStateNormal];
                _paySuccessBtn.enabled = NO;
                _paySuccessBtn.backgroundColor = KBASEBGCOLOR;
                [_paySuccessBtn setTitleColor:KREDCOLOR forState:UIControlStateNormal];

                
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
